package com.hyny.framework.platform.system.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.github.yulichang.wrapper.MPJLambdaWrapper;


import com.hyny.framework.platform.system.annotation.Log;
import com.hyny.framework.platform.system.base.PageBean;
import com.hyny.framework.platform.system.entity.dto.DataPowerTypeDTO;
import com.hyny.framework.platform.system.entity.param.UserAddUpdateParam;
import com.hyny.framework.platform.system.entity.param.UserDataPowerParam;
import com.hyny.framework.platform.system.entity.param.UserParam;
import com.hyny.framework.platform.system.entity.pojo.SysUser;
import com.hyny.framework.platform.system.entity.pojo.SysUserDataPower;
import com.hyny.framework.platform.system.entity.pojo.SysUserRole;
import com.hyny.framework.platform.system.entity.vo.DataPowerTypeVO;
import com.hyny.framework.platform.system.entity.vo.UserDataPowerVO;
import com.hyny.framework.platform.system.entity.vo.UserVO;
import com.hyny.framework.platform.system.service.*;
import com.hyny.framework.platform.system.utils.bean.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户信息(SysUser)表控制层
 *
 * @author 张崇阳
 * @since 2023-12-13 10:07:57
 */
@Api(tags ="用户管理")
@RestController
@ApiSupport(order=4)
@RequestMapping("/sysUser")
@Slf4j
public class SysUserController {
    /**
     * 服务对象
     */
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserDataPowerService sysUserDataPowerService;

    @Autowired
    private SysDataPowerService sysDataPowerService;

    @Autowired
    private ILoginService iLoginService;

    @Log(value = "分页查询用户列表")
    @ApiOperation(value = "分页查询用户列表")
    @GetMapping("/page/{pageNum}/{pageSize}")
    @ApiOperationSupport(order = 1)
    public Result<PageBean<UserVO>> userPage(@ApiParam(value = "页码", required = true)
                            @PathVariable(value = "pageNum") Long pageNum,
                                             @ApiParam(value = "页条数", required = true)
                            @PathVariable(value = "pageSize") Long pageSize,
                                             UserParam param){
        Page page = new Page(pageNum, pageSize);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StrUtil.isNotBlank(param.getNickName()),SysUser::getNickName,param.getNickName());
        lambdaQueryWrapper.like(StrUtil.isNotBlank(param.getUserName()),SysUser::getUserName,param.getUserName());
        lambdaQueryWrapper.like(StrUtil.isNotBlank(param.getPhone()),SysUser::getPhone,param.getPhone());
        lambdaQueryWrapper.like(StrUtil.isNotBlank(param.getEmail()),SysUser::getEmail,param.getEmail());
        lambdaQueryWrapper.like(param.getIsEnabled()!=null,SysUser::getIsEnabled,param.getIsEnabled());
        IPage<UserVO> iPage = sysUserService.page(page, lambdaQueryWrapper);
        iPage.setRecords(BeanUtil.copyToList(iPage.getRecords(),UserVO.class));
        return Result.okPage(iPage);
    }



    @Log(value = "添加用户信息",persisted = true)
    @ApiOperation(value = "添加用户信息")
    @ApiOperationSupport(order = 2)
    @PostMapping("/add")
    public Result userAdd( @RequestBody UserAddUpdateParam param){
        SysUser user = new SysUser();

        if(param.getExpiredDate()==null){
            param.setExpiredDate(DateUtil.offset(new Date(), DateField.YEAR,1));

        }
        BeanUtil.copyProperties(param, user);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(param.getPassword()));

        sysUserService.save(user);
        updateUserRole(user.getId(),param.getRoleIds());

        return Result.ok();
    }





    @Log(value = "修改用户信息",persisted = true)
    @ApiOperation(value = "修改用户信息")
    @ApiOperationSupport(order = 4)
    @PutMapping("/put/{id}")
    public Result userUpdate(@ApiParam(value = "用户编码", required = true) @PathVariable("id") String id, @RequestBody UserAddUpdateParam param) {
        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(SysUser::getNickName,param.getNickName());
        lambdaUpdateWrapper.set(SysUser::getUserName,param.getUserName());
        lambdaUpdateWrapper.set(SysUser::getPhone,param.getPhone());
        lambdaUpdateWrapper.set(SysUser::getEmail,param.getEmail());
        lambdaUpdateWrapper.set(SysUser::getIsEnabled,param.getIsEnabled());
        lambdaUpdateWrapper.set(param.getExpiredDate()!=null,SysUser::getExpiredDate,param.getExpiredDate());
        lambdaUpdateWrapper.eq(SysUser::getId,id);


        sysUserService.update(lambdaUpdateWrapper);
        updateUserRole(Long.valueOf(id),param.getRoleIds());
        iLoginService.logoutUser(Long.valueOf(id));
        return Result.ok();
    }



    @Log(value = "修改用户密码",persisted = true)
    @ApiOperation(value = "修改用户密码")
    @ApiOperationSupport(order = 4)
    @PutMapping("/putPassword/{id}")
    public Result userUpdatePassword(@ApiParam(value = "用户编码", required = true) @PathVariable("id") String id, @ApiParam(value = "用户新密码", required = true)@RequestBody String password) {
        LambdaUpdateWrapper<SysUser> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        lambdaUpdateWrapper.set(SysUser::getPassword,passwordEncoder.encode(password));
        lambdaUpdateWrapper.eq(SysUser::getId,id);
        sysUserService.update(lambdaUpdateWrapper);
        iLoginService.logoutUser(Long.valueOf(id));
        return Result.ok();
    }


    @Log(value = "删除用户信息",persisted = true)
    @ApiOperation(value = "删除用户信息")
    @ApiOperationSupport(order = 5)
    @DeleteMapping("/delete/{id}")
    public Result userDelete(@ApiParam(value = "用户编码", required = true) @PathVariable("id") String id) {
        sysUserService.removeById(id);
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,id));
        sysUserDataPowerService.remove(new LambdaQueryWrapper<SysUserDataPower>().eq(SysUserDataPower::getUserId, id));
        iLoginService.logoutUser(Long.valueOf(id));
        return Result.ok();
    }





    @ApiOperation(value = "获取数据权限类型")
    @ApiOperationSupport(order =6)
    @GetMapping("/dataPowerTypeList")
    public Result<List<DataPowerTypeVO>> dataPowerTypeList() {
       return Result.ok(sysDataPowerService.dataPowerTypeList());
    }




    @ApiOperation(value = "获取数据权限子集")
    @ApiOperationSupport(order =7)
    @GetMapping("/dataPowerChild")
    public Result<DataPowerTypeVO> dataPowerChild( DataPowerTypeDTO dto) {
        return Result.ok(sysDataPowerService.dataPowerChild(dto));
    }



    @Log(value = "用户绑定数据权限",persisted = true)
    @ApiOperation(value = "用户绑定数据权限")
    @ApiOperationSupport(order =8)
    @PostMapping("/addUserDataPower/{userid}")
    public Result addUserDataPower(@ApiParam(value = "用户编号", required = true) @PathVariable("userid") String userid,@RequestBody List<UserDataPowerParam> userDataPowerParams){
        //清空原有数据权限
        sysUserDataPowerService.remove(new LambdaQueryWrapper<SysUserDataPower>().eq(SysUserDataPower::getUserId,userid));
        //添加新的数据权限

        List<SysUserDataPower> sysUserDataPowers=BeanUtil.copyToList(userDataPowerParams,SysUserDataPower.class);
        sysUserDataPowers.forEach(ud->ud.setUserId(Long.valueOf(userid)));
        sysUserDataPowerService.saveBatch(sysUserDataPowers);
        iLoginService.logoutUser(Long.valueOf(userid));
        return Result.ok();
    }
    @ApiOperation(value = "查询用户数据权限")
    @ApiOperationSupport(order =9)
    @PostMapping("/getUserDataPower/{userid}")
    public Result<List<UserDataPowerVO>> getUserDataPower(@ApiParam(value = "用户编号", required = true) @PathVariable("userid") String userid){
        MPJLambdaWrapper<SysUserDataPower> mpjLambdaWrapper=new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(SysUserDataPower.class);
        mpjLambdaWrapper.eq(SysUserDataPower::getUserId,userid);
        return Result.ok(sysUserDataPowerService.selectJoinList(UserDataPowerVO.class,mpjLambdaWrapper));
    }





    /**
     * 变更用户角色信息
     * @param userId 用户id
     * @param roleIds 角色编码
     */
    public void updateUserRole(Long userId,List<String> roleIds){
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,userId));
        if(roleIds!=null&&roleIds.size()>0){
            List<SysUserRole> userRoleList = new ArrayList<>();
            roleIds.forEach(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Long.parseLong(roleId));
                userRoleList.add(userRole);
            });
            sysUserRoleService.saveBatch(userRoleList);
        }
    }


}

